// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.googlesource.gerrit.plugins.examples.topmenu;

import com.google.common.collect.Lists;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.extensions.client.MenuItem;
import com.google.gerrit.extensions.webui.TopMenu;
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class HelloTopMenu implements TopMenu {

  private static final Logger log = LoggerFactory.getLogger(HelloTopMenu.class);

  private final List<MenuEntry> menuEntries;

  private static List<String> userList = new ArrayList<>();

  {
    String propertiesWay = System.getProperty("user.dir") + File.separator + "conf" + File.separator
        + "conf.properties";
    PropContainer pro = PropContainer.getInstance(propertiesWay);
    String userListProperty = pro.getProperty("user-list");
    String[] split = userListProperty.split(",");
    userList = Arrays.asList(split);
    log.info("userList读取完毕:{}", userList);
  }

  @Inject
  public HelloTopMenu(@PluginName String pluginName, Provider<CurrentUser> userProvider)
      throws UnsupportedEncodingException {
    menuEntries = Lists.newArrayListWithCapacity(2);
    if (userProvider.get().isIdentifiedUser()
        && userList.contains(userProvider.get().getLoggableName())) {
      log.info("已登录");
      String baseUrl = "/q/status:open?type=search";
      List<MenuItem> menuItems = Lists.newArrayListWithCapacity(2);
      menuItems.add(new MenuItem("Search", baseUrl));

      menuEntries.add(new MenuEntry("SEARCH", menuItems));
    }

  }

  @Override
  public List<MenuEntry> getEntries() {
    return menuEntries;
  }
}
